import React, { useState } from 'react';
import { Layout, Menu, Typography, Button, Drawer } from 'antd';
import type { MenuProps } from 'antd';
import {
  DashboardOutlined,
  SearchOutlined,
  TeamOutlined,
  MenuOutlined,
  QuestionCircleOutlined,
  // 遥测点相关
  DotChartOutlined,
  DatabaseOutlined,
  FolderOutlined,
  // 团队相关
  UsergroupAddOutlined,
} from '@ant-design/icons';
import { useNavigate, useLocation, useParams } from 'react-router-dom';

const { Header, Sider, Content } = Layout;
const { Title, Text } = Typography;

interface NavigationProps {
  children: React.ReactNode;
  title?: string;
  subtitle?: string;
}

const Navigation: React.FC<NavigationProps> = ({
  children,
  title = 'UMA/UKM 分析平台',
  subtitle
}) => {
  const [collapsed, setCollapsed] = useState(false);
  const [mobileDrawerVisible, setMobileDrawerVisible] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const params = useParams();
  const currentPointId = params.pointId;

  // 检测屏幕大小
  React.useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };

    checkMobile();
    window.addEventListener('resize', checkMobile);

    return () => {
      window.removeEventListener('resize', checkMobile);
    };
  }, []);

  // 菜单项配置
  const menuItems: MenuProps['items'] = [
    {
      key: '/introduction',
      icon: <QuestionCircleOutlined />,
      label: '技术介绍',
    },
    {
      key: '/dashboard',
      icon: <DashboardOutlined />,
      label: '仪表板',
    },
    {
      type: 'divider',
    },
    {
      key: 'telemetry',
      icon: <DotChartOutlined />,
      label: '遥测点管理',
      children: [
        {
          key: '/analysis/points',
          icon: <DatabaseOutlined />,
          label: '遥测点列表',
        },
        {
          key: '/analysis/directory-list',
          icon: <FolderOutlined />,
          label: '目录列表',
        },
        {
          key: '/search',
          icon: <SearchOutlined />,
          label: '搜索遥测点',
        },
      ],
    },
    {
      key: 'teams',
      icon: <TeamOutlined />,
      label: '团队管理',
      children: [
        {
          key: '/teams',
          icon: <TeamOutlined />,
          label: '团队列表',
        },
        {
          key: '/teams/create',
          icon: <UsergroupAddOutlined />,
          label: '创建团队',
        },
      ],
    },
  ];

  // 动态菜单项配置（用于详情页面的特殊菜单）
  const getDynamicMenuItems = (): MenuProps['items'] => {
    // 如果在遥测点详情页面，修改遥测点管理菜单以显示当前页面
    if (currentPointId) {
      return menuItems.map((item): any => {
        if (item && 'key' in item && item.key === 'telemetry') {
          return {
            ...item,
            children: [
              {
                key: `/analysis/points/${currentPointId}`,
                icon: <DatabaseOutlined />,
                label: '遥测点详情',
                style: { backgroundColor: '#e6f7ff', fontWeight: 'bold' }
              },
              {
                key: '/analysis/points',
                icon: <DatabaseOutlined />,
                label: '遥测点列表',
              },
              {
                key: '/analysis/directory-list',
                icon: <FolderOutlined />,
                label: '目录列表',
              },
              {
                key: '/search',
                icon: <SearchOutlined />,
                label: '搜索遥测点',
              },
            ],
          };
        }
        return item;
      });
    }
    return menuItems;
  };

  // 处理菜单点击
  const handleMenuClick = ({ key }: { key: string }) => {
    navigate(key);
    if (isMobile) {
      setMobileDrawerVisible(false);
    }
  };

  // 获取当前选中的菜单项
  const getSelectedKeys = () => {
    const path = location.pathname;
    const dynamicItems = getDynamicMenuItems();

    if (!dynamicItems) {
      return ['/dashboard'];
    }

    // 精确匹配
    if (dynamicItems!.some(item => item && 'key' in item && item.key === path)) {
      return [path];
    }

    // 查找子菜单匹配
    for (const item of dynamicItems!) {
      if (item && 'children' in item && item.children) {
        for (const child of item.children) {
          if (child && 'key' in child && child.key === path) {
            return [child.key];
          }
        }
      }
    }

    // 默认选中仪表板
    return ['/dashboard'];
  };

  // 获取展开的菜单项
  const getOpenKeys = () => {
    const path = location.pathname;
    const dynamicItems = getDynamicMenuItems();
    const openKeys: string[] = [];

    if (!dynamicItems) {
      return openKeys;
    }

    for (const item of dynamicItems!) {
      if (item && 'children' in item && item.children && 'key' in item && item.key) {
        for (const child of item.children) {
          if (child && 'key' in child && child.key === path) {
            openKeys.push(String(item.key));
            break;
          }
        }
      }
    }

    return openKeys;
  };

  // 渲染导航菜单
  const renderMenu = () => {
    const itemsToUse = getDynamicMenuItems();
    return (
      <Menu
        theme="light"
        mode="inline"
        selectedKeys={getSelectedKeys()}
        defaultOpenKeys={getOpenKeys()}
        items={itemsToUse}
        onClick={handleMenuClick}
        style={{
          borderRight: 0,
          height: '100%',
          paddingTop: '16px'
        }}
      />
    );
  };

  // 渲染头部
  const renderHeader = () => (
    <Header
      style={{
        padding: '0 24px',
        background: '#fff',
        borderBottom: '1px solid #f0f0f0',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        flexWrap: 'wrap',
        gap: '8px',
        minHeight: '64px',
        height: 'auto'
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', flex: '1', minWidth: 0 }}>
        {isMobile && (
          <Button
            type="text"
            icon={<MenuOutlined />}
            onClick={() => setMobileDrawerVisible(true)}
            style={{ marginRight: '16px' }}
          />
        )}
        <div style={{ flex: 1, minWidth: 0, lineHeight: '1.2' }}>
          <Title level={4} style={{
            margin: 0,
            color: '#1890ff',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            lineHeight: '1.2',
            marginBottom: subtitle ? '2px' : '0'
          }}>
            {title}
          </Title>
          {subtitle && (
            <Text
              type="secondary"
              style={{
                fontSize: '14px',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                display: 'block',
                lineHeight: '1.2'
              }}
            >
              {subtitle}
            </Text>
          )}
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', flexShrink: 0 }}>
        <Text type="secondary" style={{ fontSize: '12px', color: '#999', whiteSpace: 'nowrap' }}>
          UmaInsight Platform
        </Text>
      </div>
    </Header>
  );

  // 移动端抽屉菜单
  const renderMobileDrawer = () => (
    <Drawer
      title="菜单导航"
      placement="left"
      onClose={() => setMobileDrawerVisible(false)}
      open={mobileDrawerVisible}
      bodyStyle={{ padding: 0 }}
      width={280}
    >
      {renderMenu()}
    </Drawer>
  );

  // 桌面端侧边栏
  const renderDesktopSidebar = () => (
    <Sider
      collapsible
      collapsed={collapsed}
      onCollapse={setCollapsed}
      width={280}
      style={{
        background: '#fff',
        borderRight: '1px solid #f0f0f0',
        minHeight: '100vh',
      }}
    >
      {renderMenu()}
    </Sider>
  );

  if (isMobile) {
    return (
      <Layout style={{ minHeight: '100vh' }}>
        {renderHeader()}
        <Content style={{ margin: 0, minHeight: 'calc(100vh - 80px)', transition: 'min-height 0.2s ease' }}>
          {children}
        </Content>
        {renderMobileDrawer()}
      </Layout>
    );
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {renderDesktopSidebar()}
      <Layout>
        {renderHeader()}
        <Content
          style={{
            margin: '24px',
            minHeight: 'calc(100vh - 80px - 48px)',
            background: '#f5f5f5',
            transition: 'min-height 0.2s ease'
          }}
        >
          {children}
        </Content>
      </Layout>
    </Layout>
  );
};

export default Navigation;